<?php

namespace App\HttpController\Admin;

use App\HttpController\Common;
use App\Utils\Code;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\HttpAnnotation\AnnotationTag\Di;

class Base extends Common
{

    /**
     * 无需验证接口
     */
    protected static $notAuthList = [
        '/admin/adminUser/login',
    ];

    protected static $userInfo = [];

    /**
     * @Di(key="adminUser")
     */
    protected $adminUser;

    /**
     * @Di(key="adminMenu")
     */
    protected $adminMenu;

    /**
     * @Di(key="adminNode")
     */
    protected $adminNode;

    public function onRequest(?string $action) : bool
    {
        $request = $this -> request();

        $path = $request -> getUri() -> getPath();
        if (!in_array($path, self::$notAuthList)) {
            if (!$token = $request -> getHeaderLine('token')) return $this -> renderError(Code::TOKEN_IS_EMPTY);
            if (!$info = $this -> adminUser -> getAuthUserInfo($token)) return $this -> renderError(Code::TOKEN_IS_EXPIRE);
            self::$userInfo = $info;

            // 获取菜单列表
            $where = ['id' => [explode(',', self::$userInfo['menu_ids'] ?? ''), 'in']];
            $field = ['node_ids'];
            $menuList = $this -> adminMenu -> allList(['where' => $where, 'field' => $field]);
            if (!$menuList) return $this -> renderError(Code::IS_NOT_OPRATE_AUTH);

            // 通过菜单获取节点列表
            $nodeIds = array_column($menuList, 'node_ids');
            $where = ['id' => [explode(',', implode(',', $nodeIds)), 'in']];
            $field = ['path'];
            $nodeList = $this -> adminNode -> allList(['where' => $where, 'field' => $field]);
            if (!$nodeList) return $this -> renderError(Code::IS_NOT_OPRATE_AUTH);
            $nodeList = array_column($nodeList, 'path');
            // 判断请求是否授权
            if (!in_array($path, $nodeList)) return $this -> renderError(Code::IS_NOT_OPRATE_AUTH);;
        }

        ContextManager::getInstance()->set('context',time());
        return true;
    }

}